package YAPclient;
import YAPenvironment.YAPconstant.Command;
import YAPenvironment.YAPconstant;

/**
 * @author Xaro/Kath/DMaggi/Daniel<br>
 * Class to check if the server is still available. Disconnects otherwise
 */
public class IsAliveThread extends Thread{
	
	private long timeSent = System.currentTimeMillis();
	
	/**
	 * @see java.lang.Thread#run()
	 * Checks if the {@link YAPconstant.C_ALIVE_TIMEOUT} has run out and sends a isAlive to the server.
	 */
	@Override
	public void run(){
		while(true){
			if (DataModul.running){
				long currTime = System.currentTimeMillis();
				if(currTime-timeSent > YAPconstant.C_ALIVE_TIMEOUT)
				{
					//disconnect
					System.out.println("***Verbindung zum Server unterbrochen - Client wird beendet***");
					System.exit(0);
				}
				DataModul.parseThread.writeMessage(Command.isAliveClient.toString()+YAPconstant.C_SEPARATOR);
	
				try{
					Thread.sleep(YAPconstant.C_ALIVE_INTERVAL); 
				}catch(Exception e){
					if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
				}
			}
			else{
				try {
					sleep(DataModul.sleepTime);
				} catch (InterruptedException e) {
					if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
				}
			}
		}
	}	
	
	
	/**
	 * Sets the time when the last isAlive has been arrived
	 * @param milis Time in ms
	 */
	public void setTimeSent(long milis){
		timeSent = milis;
	}
}
